import bluetoothManager from '@/src/utility/bluetooth.js';

const state = {
  isConnected: false,
  deviceId: null,
  connectedDevice: null,
  connectionCallback: null
};

const mutations = {
  SET_CONNECTION(state, { isConnected, deviceId, device }) {
    state.isConnected = isConnected;
    state.deviceId = deviceId;
    state.connectedDevice = device;
  },
  SET_CONNECTION_CALLBACK(state, callback) {
    state.connectionCallback = callback;
  }
};

const actions = {
  async connectDevice({ commit }, deviceId) {
    try {
      await bluetoothManager.connectDevice(deviceId);
      commit('SET_CONNECTION', {
        isConnected: true,
        deviceId,
        device: bluetoothManager.connectedDevice
      });
      return true;
    } catch (error) {
      console.error('蓝牙连接失败:', error);
      return false;
    }
  },
  
  disconnectDevice({ commit }) {
    try {
      bluetoothManager.disconnectDevice();
      commit('SET_CONNECTION', {
        isConnected: false,
        deviceId: null,
        device: null
      });
    } catch (error) {
      console.error('断开蓝牙连接失败:', error);
    }
  },
  
  setConnectionCallback({ commit }, callback) {
    commit('SET_CONNECTION_CALLBACK', callback);
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}; 